#include "Shape.h"


Shape::Shape(void)
{
	name="Shape";
	bNormal = false;
	bRotateAroundOwnAxis = false;
	list_intersect.clear();
}

Shape::~Shape(void)
{
}


MVertex getVertex(const MVertex &p1, const MVertex &p2) {
	MVertex v;
	v.point[0] = p2.point[0]-p1.point[0];
	v.point[1] = p2.point[1]-p1.point[1];
	v.point[2] = p2.point[2]-p1.point[2]; 
	return v;
}

void calculateNormal(MVertex *p, const MVertex &v, const MVertex &t, 
							const MVertex &b, const MVertex &l, const MVertex &r) {
	MVertex n1, n2, n3, n4;
	n1 = getVertex(v,t).CrossProduct(getVertex(v,l));
	n2 = getVertex(v,r).CrossProduct(getVertex(v,t));
	n3 = getVertex(v,l).CrossProduct(getVertex(v,b));
	n4 = getVertex(v,b).CrossProduct(getVertex(v,r));
	(*p) = (n1+n2+n3+n4).normalize();
}

//return 1 if intersect, 0 if not
int ray_plane_intersect(MVertex p, MVertex d, MVertex v1, MVertex v2, MVertex v3, 
	list<MVertex>&list) {
		MVertex norm = ((v1-v2).CrossProduct(v3-v1)).normalize();
		if(isEqual(norm*d,0))	//line is parallel to the plane 
			return 0;
		//normal * Vector(v0 to p+td) =0
		float t = (norm.x()*(v1.x()-p.x()) + norm.y()*(v1.y()-p.y()) + norm.z()*(v1.z()-p.z()))/
			(d.x()*norm.x() + d.y()*norm.y() + d.z()*norm.z());
		float fx = p.x() + d.x() * t;
		float fy = p.y() + d.y() * t;
		float fz = p.z() + d.z() * t;
		MVertex v(fx,fy,fz);
		//check whether intersection point is inside the triangle
		if((v1-v2).CrossProduct((v-v1)).isSameDirection(norm) &&
			(v3-v1).CrossProduct((v-v3)).isSameDirection(norm) &&
			(v2-v3).CrossProduct((v-v2)).isSameDirection(norm)) {
				list.push_back(v);
				return 1;
		}
		return 0;
}